import { reqUserLogin, reqUserLogout } from "@/api/index"

const state = {
  userInfo: {
    name: localStorage.getItem("userName"),
    token: localStorage.getItem("userToken"),
  },
}
const actions = {
  // 登入
  async userLogin({ commit }, user) {
    const result = await reqUserLogin(user)
    if (result.code === 200) {
      console.log("成功")
      commit("USER_LOGIN", result.data)
      localStorage.setItem("userName", result.data.name)
      localStorage.setItem("userToken", result.data.token)
      // return true
    } else {
      console.log("失败", result.message)
    }
  },

  // 退出
  async userLogout({ commit }) {
    const result = await reqUserLogout()
    if (result.code === 200) {
      console.log("退出登入成功")
      localStorage.removeItem("userName")
      localStorage.removeItem("userToken")
      commit("REMOVE_USER_INFO")
    } else {
      console.log("退出登入失败", result.message)
    }
  },
}
const mutations = {
  // 保存数据
  USER_LOGIN(state, payload) {
    state.userInfo.name = payload.name
    state.userInfo.token = payload.token
  },
  // 删除用户数据
  REMOVE_USER_INFO(state) {
    state.userInfo.name = ""
    state.userInfo.token = ""
  },
}
const getters = {}

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters,
}
